#include <iostream>
#include <memory>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "LogMessage.hpp"
#include "ExistReason.hpp"

void Usage()
{
    Log::LogMessage(Error, "Please enter:  ./Client [ip] port");
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        return USE_ERROR_MANUAL;
    }

    std::string ip = argv[1];
    uint16_t port = atoi(argv[argc - 1]);
    // 创建套接字
    int clientsocket = socket(AF_INET, SOCK_DGRAM, 0);
    if (clientsocket < 0)
    {
        Log::LogMessage(Error, "create socket error");
        exit(CREATE_SOCKET_ERROR);
    }
    Log::LogMessage(Debug, "create socket success, socket: %d", clientsocket);

    // 直接给服务器send，系统会自动帮我们bind
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    while (true)
    {
        std::string buffer;
        std::getline(std::cin, buffer);
        if (buffer == "quit")
        {
            close(clientsocket);
            break;
        }
        sendto(clientsocket, buffer.c_str(), buffer.size(), 0, (sockaddr *)&addr, sizeof(addr));

        sockaddr_in add;
        memset(&add, 0, sizeof(add));
        socklen_t addlen = sizeof(add);
        char mes[1024];
        int n = recvfrom(clientsocket, mes, sizeof(mes) - 1, 0, (sockaddr *)&add, &addlen);
        std::string ip = inet_ntoa(addr.sin_addr);
        uint16_t port = ntohs(addr.sin_port);
        if (n > 0)
        {
            mes[n] = 0;
            std:: cout << mes;
        }
    }

    return 0;
}